<template>
  <a-select :placeholder="placeholder" ref="select" v-model:value="selectedOption" @change="onChange" option-filter-prop="title">
    <a-select-option v-for="(item, index) in effectItems" :key="item[valuePropName]" :title="item[labelPropName]">{{ item[labelPropName] }}</a-select-option>
  </a-select>
</template>
<script>/**
 * 进一步封装Antdv的Select组件，简化代码量
 */
export default {
  name: 'SagSelect',
  inject: ['getDictByType'],
  props: {
    datasource: { type: [Array, String, Function], default: null },
    labelPropName: { type: [String, Number], default: 'label' },
    valuePropName: { type: [String, Number], default: 'value' },
    firstName: { type: String, default: null },
    firstValue: { type: [String, Number], default: null },
    value: { type: [String, Number, Array, Object], default: null },
    includeDisabled: { type: Boolean, default: false },
    numberValue: { type: Boolean, default: false },
    placeholder: { type: String, default:null},
  },
  emits: ['input', 'change', 'update:value'],
  data() {
    return {
      items: [],
      selectedOption: this.value,
    };
  },
  computed: {
    effectItems() {
      const { firstName, firstValue, labelPropName, valuePropName, items } = this;
      if(this.numberValue){
        items.forEach(item => item[valuePropName] = Number(item[valuePropName]))
      }
      let finalItems = items;
      if (firstName !== null && typeof firstName !== 'undefined') {
        finalItems = [
          {
            [labelPropName]: firstName,
            [valuePropName]: firstValue,
          },
        ].concat(items);
      }
      return finalItems;
    },
  },
  watch: {
    datasource: {
      immediate: true,
      handler(val, old) {

        if (Array.isArray(val)) {
          this.items.splice(0, this.items.length, ...val);
        } else if (typeof val === 'string' && val.length > 0) {
          this.items.splice(0, this.items.length);
          this.loadDictData();
        } else if (val instanceof Function) {
          this.items.splice(0, this.items.length);
          val()
              .then(resp => {
                if (resp.success && resp.data && resp.data.length > 0) {
                  this.items.push(...resp.data);
                }
              })
              .catch(() => {
                console.warn('没有获得数据源数据:' + this.datasource);
              });
        }
      },
    },
    value: {
      immediate: true,
      handler(val) {
        this.selectedOption = val;
      },
    },
  },
  methods: {
    loadDictData() {
      // 加载数据字典数据
      this.getDictByType(this.datasource, this.includeDisabled ? 1 : 0).then(resp => {
        if (resp && resp.success && resp.data && resp.data.length > 0) {
          const options = resp.data.map(x => ({
            [this.labelPropName]: x[1],
            [this.valuePropName]: x[0],
          }));
          this.items.push(...options);
          this.$nextTick(() => {
            this.selectedOption = this.value;
          });
        } else {
          console.warn('没有获取到数据源数据:' + this.datasource);
        }
      });
    },

    onChange(val){
      this.$emit('update:value', val);
      const item = this.effectItems.find(x => x[this.valuePropName] === val);
      this.$emit('change', val, item);
    }
  },

};
</script>
